const fs = require('fs')
const path = require('path')
const { BaseGenerator } = require('scaffolds-common')

module.exports = class extends BaseGenerator {
  constructor(args, opts) {
    super(args, opts)
  }

  initializing () {
    this.preventLoadInGeneratorDir()
  }

  async prompting() {
    this.answers = await this.prompt([
      {
        type: "input",
        name: "name",
        message: "项目名称",
        default: this.appname // Default to current folder name
      },
      {
        type: 'confirm',
        name: 'engineering',
        message: '是否生成支持工程化开发的模块（overcommit、rubocop）',
        default: false
      },
      {
        type: 'confirm',
        name: 'swagger',
        message: '是否支持生成 Swagger 文档',
        default: false
      }
    ])
  }

  writing() {
    const rootDir = this.templatePath()
    function eachFile(filePath, callback) {
      fs.readdir(filePath, function(err, files) {
        if (err) {
          console.error('读取文件列表失败', err)
        } else {
          files.forEach(function(filename) {
            const childFilePath = path.join(filePath, filename)
            fs.stat(childFilePath, function(err, stats) {
              if(err) {
                console.error('获取文件stats失败', err)
              } else {
                if (stats.isFile()) {
                  const relativePath = path.relative(rootDir, childFilePath)
                  callback(relativePath)
                } else if (stats.isDirectory()) {
                  eachFile(childFilePath, callback)
                }
              }
            })
          })
        }
      })
    }    

    eachFile(rootDir, filePath => {
      if (!this._rejectFile(filePath)) {
        this.fs.copyTpl(
          this.templatePath(filePath),
          this.destinationPath(filePath),
          this.answers
        )
      }
    })
  }

  _rejectFile (filePath) {
    if (!this.answers.engineering) {
      return ['.rubocop.yml', '.overcommit.yml', 'docs/overcommit-and-rubocop.md'].indexOf(filePath) !== -1
    }
  }
}
